import random,os,sys 
sys.path.append(".")
import shutil  

from video.scan import *
from video.crop import *


def read_input_txt(fn):
    with open(fn, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        res = []
        for line in lines:
            name, second = line.strip().split(SPLIT_ITEM)
            res.append( ( name, int(second) ) )
    return res 


# int( 90 * (end / tol ) + 1  )

#  -> [(id, name, start, dur  ), ]
def gen_the_split_time_range(name_sec_tup_list, time_need):
    time_unit = 4 # 5s
    skip_time = 5
    tol_time = 0
    for name, end in name_sec_tup_list: 
        tol_time += end 

    ## 随机切割
    final_res = []
    for name, end in name_sec_tup_list: 
        start = random.randint(0, 5) 
        res = []
        for i in range(skip_time+start, end-time_unit, time_unit):
            res.append( (name, i) ) 

        need_frame =  int( time_need * (end / tol_time ) / 4) + 1 
        res = random.sample(res, need_frame)
        
        final_res.extend(res)

    # 分配顺序
    rd_seq = list(range(0, len(final_res)))
    random.shuffle(rd_seq)

    real_res=[]
    j = 0
    for i in final_res:
        item = ( rd_seq[j], i[0],i[1], time_unit  )
        real_res.append(item)
        print(item)
        j+=1
 
    print( len(real_res) * time_unit )

    return real_res



if __name__ == "__main__":
    # 设置基本工作区
    base_dir = "./工作区3金字塔2"
    video_out_dir  = os.path.join(base_dir, "视频")
    if not os.path.exists( video_out_dir ) :
        os.mkdir(video_out_dir )
    else: 
        shutil.rmtree(video_out_dir)  
        os.mkdir(video_out_dir) 


    # 输入视频片段，来自于scan py
    res = read_input_txt( os.path.join(base_dir, "input.txt") )
    print(res)

    ## 输入时间，随机裁剪
    T =  110 # s
    real_split_param = gen_the_split_time_range(res, T)  # 随机裁剪

    for param in real_split_param:
        id, name, start, dur  = param
        # src,outdir, (start, dur), id
        cut_time_video(  name, video_out_dir, (start, dur),  id  )
        print("succ", name)
    print("end")


    # cmd = 'ffmpeg -f concat -safe 0 -i file.txt -c copy output.mp4'
    # os.system(cmd)




